package search

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"wechat/global"
	"wechat/handle/model"
	"wechat/handle/request"
	"wechat/pkg"
)

// 用户注册
func AddUser(c *gin.Context) {
	var form request.AddUser
	if err := c.ShouldBind(&form); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var user model.User
	if err := user.VeryPhone(global.DB, form.Phone); err == nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "手机号已注册,请登录",
		})
		return
	}

	result, _ := global.Rdb.Get(global.Ctx, "sendSms_"+form.Phone).Result()
	if result != form.Sms {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "短信验证码错误",
		})
		return
	}

	user = model.User{
		Phone:    form.Phone,
		Password: pkg.MD5(form.Password),
		Username: fmt.Sprintf("游客_%d", rand.Intn(900)+100),
		Image:    "C:\\Users\\yangj\\Pictures\\Camera Roll\\1.PNG",
	}

	if err := user.AddUser(global.DB); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "注册失败",
		})
		return
	}

	marshal, err := json.Marshal(user)
	if err != nil {
		return
	}
	global.Rdb.Set(global.Ctx, "listUser", marshal, time.Minute)

	c.JSONP(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户注册成功",
	})

}

// 登录
func Login(c *gin.Context) {
	var form request.Login
	if err := c.ShouldBind(&form); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var user model.User
	if err := user.VeryPhone(global.DB, form.Phone); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "手机号未注册",
		})
		return
	}

	result, _ := global.Rdb.Get(global.Ctx, "sendSms_"+form.Phone).Result()
	if result != form.Sms {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "短信验证码错误",
		})
		return
	}

	if user.Password != pkg.MD5(form.Password) {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}

	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return
	}

	c.JSONP(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"Data": gin.H{
			"phone":    user.Phone,
			"username": user.Username,
			"image":    user.Image,
			"token":    handler,
		},
	})

}

// 搜索
func Search(c *gin.Context) {
	var form request.SearchUser
	if err := c.ShouldBind(&form); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var user model.User
	searchUser, err := user.SearchUser(global.DB, form.Phone, form.Username)
	if err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "搜索失败",
		})
		return
	}

	c.JSONP(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"Data": map[string]interface{}{
			"list": searchUser,
		},
	})

}
